package com.easy.framework.common.utils;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 
 * @author Yang Huijing
 *
 */
public class ThreadPool {
	//线程库
	private List<Worker> workers;
	//任务队列
	private BlockingQueue<Runnable> taskQueue;
	//标记
	private volatile boolean sign = true;
	/**
	 * 
	 * @param poolSize --线程大小
	 * @param taskQueueSize --队列大小
	 */
	public ThreadPool(int poolSize, int taskQueueSize) {
		super();
		if (poolSize <= 0 || taskQueueSize <= 0) {
			throw new IllegalArgumentException("参数错误！");
		}
		this.taskQueue = new LinkedBlockingQueue<>(taskQueueSize);
		this.workers = new ArrayList<Worker>();
		for (int i = 0; i < poolSize; i++) {
			Worker w = new Worker(this);
			this.workers.add(w);
			w.start();
		}
	}
	/**
	 * 
	 * @param poolSize --线程大小
	 */
	public ThreadPool(int poolSize) {
		super();
		if (poolSize <= 0) {
			throw new IllegalArgumentException("参数错误！");
		}
		this.taskQueue = new LinkedBlockingQueue<>();
		this.workers = new ArrayList<Worker>();
		for (int i = 0; i < poolSize; i++) {
			Worker w = new Worker(this);
			this.workers.add(w);
			w.start();
		}
	}
	/**
	 * 提交任务
	 * @param task
	 * @return
	 */
	public boolean submit(Runnable task) {
		if(sign)
			return this.taskQueue.offer(task);
		return false;
	}
	/**
	 * 关闭
	 */
	public void shutdown() {
		sign=false;
	}

	private static class Worker extends Thread {
		private ThreadPool pool;

		public Worker(ThreadPool pool) {
			this.pool = pool;
		}
	    public void run(){
	    	try {
	    		//如果处于开启或者还有任务时往下执行
	    		while (this.pool.sign||pool.taskQueue.size()>0) {
					Runnable runnable =pool.taskQueue.take();
					runnable.run();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	    }
	}
	public static void main(String[] args) {
		ThreadPool t=new ThreadPool(10);
		for(int i=0;i<800;i++){
			t.submit(new Runnable(){
				@Override
				public void run() {
					//业务
//					Common.databaseLog(new Date()+"\r\n");
				}
			});
		}
	}
}
